#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
 
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <errno.h>
 
#define SERVER_PORT 10004
 
using namespace std;
 
#define MAXLINE 1024
 
int main() {
	int listenfd, connfd;
	struct sockaddr_in sockaddr;
	struct sockaddr_in clientaddr;
	int addr_len = sizeof(clientaddr);
	char buff[MAXLINE];
	int n;
	memset(&sockaddr, 0, sizeof(sockaddr));
	sockaddr.sin_family = AF_INET;
	sockaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	sockaddr.sin_port = htons(SERVER_PORT);
 
	listenfd = socket(AF_INET, SOCK_STREAM, 0);
	bind(listenfd, (struct sockaddr *)&sockaddr, sizeof(sockaddr));
	listen(listenfd, 10);
//	printf("Wait for the client information\n");
//	printf("监听端口：%d\n", SERVER_PORT);
 
	while(1){
		printf("监听端口：%d\n", SERVER_PORT);
		// clientAddr是一个传出参数，accept返回时，传出客户端的地址和端口号
		// addr_len是一个传入-传出参数，传入的是调用者提供的缓冲区的clientAddr的长度，以免缓冲区溢出
		// 传出的是一个客户端地址结构体的实际长度
		if((connfd = accept(listenfd, (struct sockaddr*)&clientaddr, (socklen_t*)&addr_len)) == -1){
			printf("accpect socket error: %s errno :%d \n", strerror(errno), errno);
		}
		printf("等待消息...\n");
		printf("IP is %s\n", inet_ntoa(clientaddr.sin_addr));
		printf("Port is %d\n", htons(clientaddr.sin_port));
 
		while(1){
			printf("读取消息：");
			n = recv(connfd, buff, MAXLINE, 0);
			buff[n] = '\0';
			printf("recv msg from client:  %s\n", buff);
			if(strcmp(buff, "quit") == 0){
				break;
			}
			printf("发送消息：\n");
			char resp[MAXLINE] = "return from server";
			if((send(connfd, resp, strlen(resp), 0)) < 0){
				printf("send mes error: %s errno : %d",strerror(errno), errno);
				exit(0);
			}
			if(strcmp(resp, "quit") == 0){
				break;
			}
		}
	}
	close(listenfd);
	return 0;
}